package cn.edu.zzuli.queue;

import java.util.Scanner;

public class ArrayQueueDemo {

    public static void main(String[] args) {
        ArrayQueue queue = new ArrayQueue(3);
		char key = ' '; 
		Scanner scanner = new Scanner(System.in);//
        boolean loop = true;
        
		while(loop) {
			System.out.println("s(show): 遍历队列");
			System.out.println("e(exit): 退出程序");
			System.out.println("a(add): 添加一个数据到队列");
			System.out.println("g(get): 从队列中取出一个数据");
			System.out.println("h(head): 显示队头元素");
			key = scanner.next().charAt(0);
			switch (key) {
			case 's':
				queue.showQueue();
				break;
			case 'a':
				System.out.println("输入一个值");
				int value = scanner.nextInt();
				queue.addQueue(value);
				break;
			case 'g': 
				try {
					int res = queue.getQueue();
					System.out.printf("取出的元素为%d\n", res);
				} catch (Exception e) {
					System.out.println(e.getMessage());
				}
				break;
			case 'h': 
				try {
					int res = queue.headQueue();
					System.out.printf("队首的元素为%d\n", res);
				} catch (Exception e) {
					System.out.println(e.getMessage());
				}
				break;
			case 'e': 
				scanner.close();
				loop = false;
				break;
			default:
				break;
            }
            
        }
        
        System.out.println("退出程序");
    }

}

//使用数组模拟队列
class ArrayQueue {
    //队列的最大容量
    private int maxSize;
    //队首
    private int front;
    //队尾
    private int rear;
    //存放的数据
    private int[] data;

    //创建一个队列
    public ArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        data = new int[maxSize];
        front = -1;//指向队列头部的前一个位置
        rear = -1;//指向队尾（指向队列的最后一个数据）
    }

    //添加数据到队列
    public void addQueue(int n) {
        if (isFull()) {
            System.out.println("队列已满");
            return;
        }

        //让队尾指针后移
        rear++;
        data[rear] = n;
    }

    //获取队列元素（出队列）
    public int getQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空,不能取数据");
        }

        //队首指针后移
        front++;
        return data[front];
    }

    //遍历队列的元素
    public void showQueue() {
        if (isEmpty()) {
            System.out.println("队列为空，没有数据");
            return;
        }
        for (int i = front+1; i <= rear; i++) {
            System.out.println(data[i]);
        }
    }

    //显示队列的头数据
    public int headQueue() {
        if(isEmpty()) {
            throw new RuntimeException("队列为空,不能取数据");
        }

        return data[front+1];
    }

    //判断队列是否满了
    public boolean isFull() {
        //如果队尾 == 最大容量-1 那么说明队列为空
        return maxSize-1 == rear;
    }

    public boolean isEmpty() {
        //队首==队尾时 说明队列为空
        return front == rear;
    }

}